<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="系统Logo" class="logo" />
        <h1 class="title">资产管理系统</h1>
        <p class="subtitle">请登录您的账号</p>
      </div>
      
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="code" v-if="showVerifyCode">
          <div class="verify-code-container">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              prefix-icon="el-icon-key"
              autocomplete="off"
              style="width: calc(100% - 120px);"
            >
            </el-input>
            <div class="verify-code-image" @click="refreshVerifyCode">
              {{ verifyCode }}
            </div>
          </div>
        </el-form-item>
        
        <el-form-item class="remember-me-container">
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <el-button type="text" class="forgot-password" @click="handleForgotPassword">忘记密码？</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
            :disabled="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p class="copyright">© 2024 资产管理系统 版权所有</p>
      </div>
    </div>
    
    <!-- 找回密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="找回密码"
      width="40%"
      :before-close="handleCloseForgotPassword"
    >
      <el-form :model="forgotPasswordForm" :rules="forgotPasswordRules" ref="forgotPasswordFormRef" class="forgot-password-form">
        <el-form-item prop="username">
          <el-input
            v-model="forgotPasswordForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="forgotPasswordForm.email"
            type="email"
            placeholder="请输入注册邮箱"
            prefix-icon="el-icon-message"
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="verificationCode">
          <div class="verify-code-container">
            <el-input
              v-model="forgotPasswordForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="el-icon-key"
              autocomplete="off"
              style="width: calc(100% - 120px);"
            >
            </el-input>
            <el-button
              type="primary"
              :disabled="countdown > 0"
              @click="sendVerificationCode"
              style="width: 110px;"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseForgotPassword">取消</el-button>
          <el-button type="primary" @click="submitForgotPassword">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      showVerifyCode: false,
      verifyCode: 'ABCD',
      loginForm: {
        username: '',
        password: '',
        code: '',
        rememberMe: false
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 4, message: '验证码长度为4个字符', trigger: 'blur' }
        ]
      },
      forgotPasswordVisible: false,
      countdown: 0,
      forgotPasswordForm: {
        username: '',
        email: '',
        verificationCode: ''
      },
      forgotPasswordRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入注册邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度为6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 从localStorage恢复记住的用户名
    const rememberedUsername = localStorage.getItem('rememberedUsername')
    if (rememberedUsername) {
      this.loginForm.username = rememberedUsername
      this.loginForm.rememberMe = true
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          this.loading = true
          
          // 模拟登录请求
          setTimeout(() => {
            // 验证逻辑
            if (this.loginForm.username === 'admin' && this.loginForm.password === '123456') {
              // 保存记住的用户名
              if (this.loginForm.rememberMe) {
                localStorage.setItem('rememberedUsername', this.loginForm.username)
              } else {
                localStorage.removeItem('rememberedUsername')
              }
              
              // 保存登录状态到sessionStorage
              sessionStorage.setItem('isLoggedIn', 'true')
              sessionStorage.setItem('username', this.loginForm.username)
              
              this.$message.success('登录成功')
              this.$router.push('/dashboard')
            } else {
              this.$message.error('用户名或密码错误')
              // 连续失败三次显示验证码
              if (this.loginAttempts >= 2) {
                this.showVerifyCode = true
                this.refreshVerifyCode()
              }
            }
            this.loading = false
          }, 1000)
        }
      })
    },
    refreshVerifyCode() {
      // 生成随机验证码
      const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
      let code = ''
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      this.verifyCode = code
    },
    handleForgotPassword() {
      this.forgotPasswordVisible = true
    },
    handleCloseForgotPassword() {
      this.forgotPasswordVisible = false
      if (this.forgotPasswordFormRef) {
        this.$refs.forgotPasswordFormRef.resetFields()
      }
      this.countdown = 0
    },
    sendVerificationCode() {
      this.$refs.forgotPasswordFormRef.validateField(['username', 'email'], (errors) => {
        if (!errors) {
          console.log('发送验证码到邮箱:', this.forgotPasswordForm.email)
          this.startCountdown()
          this.$message.success('验证码已发送，请查收邮件')
        }
      })
    },
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    },
    submitForgotPassword() {
      this.$refs.forgotPasswordFormRef.validate((valid) => {
        if (valid) {
          console.log('提交找回密码请求:', this.forgotPasswordForm)
          this.$message.success('密码重置链接已发送到您的邮箱，请查收')
          this.handleCloseForgotPassword()
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-form-wrapper {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  position: relative;
  overflow: hidden;
}

.login-form-wrapper::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  transform: rotate(30deg);
  animation: float 10s ease-in-out infinite;
}

@keyframes float {
  0% { transform: rotate(30deg) translate(-10%, -10%); }
  50% { transform: rotate(30deg) translate(10%, 10%); }
  100% { transform: rotate(30deg) translate(-10%, -10%); }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
  z-index: 1;
}

.logo {
  height: 60px;
  margin-bottom: 15px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.login-form {
  position: relative;
  z-index: 1;
}

.verify-code-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verify-code-image {
  width: 110px;
  height: 40px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 2px;
  cursor: pointer;
  user-select: none;
}

.verify-code-image:hover {
  opacity: 0.9;
}

.remember-me-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.forgot-password {
  font-size: 13px;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-footer {
  margin-top: 20px;
  text-align: center;
  position: relative;
  z-index: 1;
}

.copyright {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.forgot-password-form {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

<style>
/* 全局样式重置 */
body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 覆盖Element Plus默认样式 */
.el-input__inner {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.el-button--primary {
  background-color: #667eea;
  border-color: #667eea;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #5a6fdd;
  border-color: #5a6fdd;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #667eea;
  border-color: #667eea;
}
</style>